package com.qf.work0625.controller;

import com.qf.work0625.entity.CandidateVoteCount;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/get")
public class GetVoteController {
    private Jedis jedis;

    public static void main(String[] args) {
        GetVoteController controller = new GetVoteController();
        String voteCountJson = controller.getVoteCount();
        System.out.println(voteCountJson);
    }

    public void VoteCountService() {
        // 连接Redis数据库
        jedis = new Jedis("172.16.1.115");
    }
    @GetMapping("/getvote")
    public String getVoteCount() {
        // 获取所有候选人的得票统计信息
        Map<String, String> voteCounts = jedis.hgetAll("vote_counts");

        // 将得票统计信息转换为JSON格式
        List<CandidateVoteCount> candidateVoteCounts = new ArrayList<>();
        for (Map.Entry<String, String> entry : voteCounts.entrySet()) {
            String candidateName = entry.getKey();
            int voteCount = Integer.parseInt(entry.getValue());
            candidateVoteCounts.add(new CandidateVoteCount(candidateName, voteCount));
        }
        String json = "{\"msg\":\"OK\",\"code\":1,\"data\":" + candidateVoteCounts.toString() + "}";

        return json;
    }
}
